<?php

// 雪里开简易预约制访客管理系统 V1.0（2025.05.20）
// 演示地址: http://fangke.chalide.cn
// 更新关注: /weivote/yuyuefangke
// 文件路径: install.php
// 文件大小: 19865 字节
// 最后修改时间: 2025-05-20 22:15:00
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权
/**
 * 安装程序
 * 功能反馈:15058593138@qq.com
 */

// 加载数据库连接配置
require_once './inc/conn.php';

// 检查是否已安装
$installed = is_installed();

// AJAX请求处理
if (isset($_GET['act'])) {
    header('Content-Type: application/json; charset=utf-8');
    
    switch ($_GET['act']) {
        case 'check': // 环境检查
            $result = [
                'code' => 0,
                'msg' => '环境检查通过',
                'data' => [
                    'php_version' => PHP_VERSION,
                    'php_check' => version_compare(PHP_VERSION, '7.1.0', '>='),
                    'mysqli' => extension_loaded('mysqli'),
                    'json' => extension_loaded('json'),
                    'db_conn' => @mysqli_connect($db_host, $db_user, $db_pass, '', $db_port) !== false,
                    'db_exists' => false
                ]
            ];
            
            // 检查数据库是否存在
            $conn = @mysqli_connect($db_host, $db_user, $db_pass, '', $db_port);
            if ($conn) {
                $query = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$db_name'";
                $res = mysqli_query($conn, $query);
                $result['data']['db_exists'] = mysqli_num_rows($res) > 0;
                mysqli_close($conn);
            }
            
            echo json_encode($result, JSON_UNESCAPED_UNICODE);
            exit;
            
        case 'install': // 安装系统
            $result = ['code' => 0, 'msg' => '安装成功', 'data' => []];
            
            try {
                // 连接数据库服务器
                $conn = @mysqli_connect($db_host, $db_user, $db_pass, '', $db_port);
                if (!$conn) {
                    throw new Exception('无法连接到数据库服务器: ' . mysqli_connect_error());
                }
                
                // 检查数据库是否存在，不存在则创建
                $query = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$db_name'";
                $res = mysqli_query($conn, $query);
                if (mysqli_num_rows($res) == 0) {
                    if (!mysqli_query($conn, "CREATE DATABASE `$db_name` CHARACTER SET utf8 COLLATE utf8_general_ci")) {
                        throw new Exception('创建数据库失败: ' . mysqli_error($conn));
                    }
                }
                
                // 选择数据库
                if (!mysqli_select_db($conn, $db_name)) {
                    throw new Exception('选择数据库失败: ' . mysqli_error($conn));
                }
                
                // 设置字符集
                mysqli_set_charset($conn, 'utf8');
                
                // 创建学生表
                $sql = "CREATE TABLE IF NOT EXISTS `stux` (
                    `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
                    `xh` varchar(50) NOT NULL COMMENT '学号',
                    `pwd` varchar(50) NOT NULL COMMENT '密码',
                    `name` varchar(50) NOT NULL COMMENT '实名',
                    `tel` varchar(20) DEFAULT NULL COMMENT '电话',
                    `type` enum('stu','sus','sys') NOT NULL DEFAULT 'stu' COMMENT '类型(学生|门卡|系统)',
                    `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态(1启用,0禁用)',
                    `memo` text COMMENT '备注',
                    PRIMARY KEY (`id`),
                    UNIQUE KEY `xh` (`xh`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='学生表';";
                if (!mysqli_query($conn, $sql)) {
                    throw new Exception('创建学生表失败: ' . mysqli_error($conn));
                }
                $result['data']['stux'] = '创建成功';
                
                // 创建访客表
                $sql = "CREATE TABLE IF NOT EXISTS `vist` (
                    `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
                    `stuid` int(11) NOT NULL COMMENT '学生ID',
                    `room` varchar(50) NOT NULL COMMENT '目标宿舍号',
                    `reason` text NOT NULL COMMENT '到访事由',
                    `vname` varchar(50) NOT NULL COMMENT '访客姓名',
                    `vtel` varchar(20) NOT NULL COMMENT '访客电话',
                    `vdate` date NOT NULL COMMENT '到访日期',
                    `vcode` varchar(10) NOT NULL COMMENT '访客码',
                    `htime` datetime DEFAULT NULL COMMENT '核销时间',
                    `huser` varchar(50) DEFAULT NULL COMMENT '核销账号',
                    PRIMARY KEY (`id`),
                    KEY `stuid` (`stuid`),
                    KEY `vcode` (`vcode`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='访客表';";
                if (!mysqli_query($conn, $sql)) {
                    throw new Exception('创建访客表失败: ' . mysqli_error($conn));
                }
                $result['data']['vist'] = '创建成功';
                
                // 创建系统设置表
                $sql = "CREATE TABLE IF NOT EXISTS `site` (
                    `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
                    `skey` varchar(50) NOT NULL COMMENT '设置键',
                    `sval` text COMMENT '设置值',
                    `memo` text COMMENT '备注',
                    PRIMARY KEY (`id`),
                    UNIQUE KEY `skey` (`skey`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='系统设置表';";
                if (!mysqli_query($conn, $sql)) {
                    throw new Exception('创建系统设置表失败: ' . mysqli_error($conn));
                }
                $result['data']['site'] = '创建成功';
                
                // 插入默认设置
                $default_settings = [
                    ['site_name', '封闭校区访客管理系统', '系统名称'],
                    ['site_desc', '简易封闭校区访客管理系统', '系统描述'],
                    ['allow_visit', '1', '是否允许访客申请(1是,0否)'],
                    ['visit_start_time', '08:00', '访客允许时间开始'],
                    ['visit_end_time', '22:00', '访客允许时间结束']
                ];
                
                foreach ($default_settings as $setting) {
                    $sql = "INSERT INTO `site` (`skey`, `sval`, `memo`) VALUES ('$setting[0]', '$setting[1]', '$setting[2]')
                            ON DUPLICATE KEY UPDATE `sval` = '$setting[1]', `memo` = '$setting[2]'";
                    mysqli_query($conn, $sql);
                }
                
                // 插入默认管理员账号
                $sql = "INSERT INTO `stux` (`xh`, `pwd`, `name`, `tel`, `type`, `status`, `memo`)
                        VALUES ('admin', '123456', '系统管理员', '', 'sys', 1, '默认管理员账号')
                        ON DUPLICATE KEY UPDATE `type` = 'sys', `status` = 1;";
                mysqli_query($conn, $sql);
                
                // 如果需要导入演示数据
                if (isset($_POST['demo']) && $_POST['demo'] == 1) {
                    // 添加学生示例数据
                    for ($i = 1; $i <= 30; $i++) {
                        $xh = 'S' . str_pad($i, 3, '0', STR_PAD_LEFT);
                        $name = '学生' . $i;
                        $tel = '1381234' . str_pad($i, 4, '0', STR_PAD_LEFT);
                        $sql = "INSERT INTO `stux` (`xh`, `pwd`, `name`, `tel`, `type`, `status`, `memo`)
                                VALUES ('$xh', '$xh', '$name', '$tel', 'stu', 1, '演示数据')
                                ON DUPLICATE KEY UPDATE `name` = '$name', `tel` = '$tel';";
                        mysqli_query($conn, $sql);
                    }
                    
                    // 添加门卡管理员示例数据
                    for ($i = 1; $i <= 5; $i++) {
                        $xh = 'M' . str_pad($i, 3, '0', STR_PAD_LEFT);
                        $name = '门卡' . $i;
                        $tel = '1391234' . str_pad($i, 4, '0', STR_PAD_LEFT);
                        $sql = "INSERT INTO `stux` (`xh`, `pwd`, `name`, `tel`, `type`, `status`, `memo`)
                                VALUES ('$xh', '$xh', '$name', '$tel', 'sus', 1, '演示数据')
                                ON DUPLICATE KEY UPDATE `name` = '$name', `tel` = '$tel';";
                        mysqli_query($conn, $sql);
                    }
                    
                    // 添加访客示例数据
                    $reasons = ['探访同学', '送东西', '学习交流', '项目合作', '其他事由'];
                    $rooms = ['A101', 'B203', 'C305', 'D407', 'E509'];
                    
                    for ($i = 1; $i <= 30; $i++) {
                        $stuid = $i;
                        $room = $rooms[array_rand($rooms)];
                        $reason = $reasons[array_rand($reasons)];
                        $vname = '访客' . $i;
                        $vtel = '1351234' . str_pad($i, 4, '0', STR_PAD_LEFT);
                        $vdate = date('Y-m-d', strtotime('+' . rand(0, 10) . ' days'));
                        $vcode = strtoupper(substr(md5($i . time()), 0, 8));
                        
                        $sql = "INSERT INTO `vist` (`stuid`, `room`, `reason`, `vname`, `vtel`, `vdate`, `vcode`)
                                VALUES ('$stuid', '$room', '$reason', '$vname', '$vtel', '$vdate', '$vcode');";
                        mysqli_query($conn, $sql);
                    }
                    
                    // 部分访客已核销
                    for ($i = 1; $i <= 10; $i++) {
                        $id = $i;
                        $htime = date('Y-m-d H:i:s', strtotime('-' . rand(1, 5) . ' days'));
                        $huser = 'M' . str_pad(rand(1, 5), 3, '0', STR_PAD_LEFT);
                        
                        $sql = "UPDATE `vist` SET `htime` = '$htime', `huser` = '$huser' WHERE `id` = $id;";
                        mysqli_query($conn, $sql);
                    }
                    
                    $result['data']['demo'] = '导入成功';
                }
                
                // 创建网站设置缓存文件
                $settings_json = [];
                $res = mysqli_query($conn, "SELECT * FROM `site`");
                while ($row = mysqli_fetch_assoc($res)) {
                    $settings_json[$row['skey']] = $row['sval'];
                }
                
                $json_content = json_encode($settings_json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
                file_put_contents('./inc/json.php', $json_content);
                
                // 关闭连接
                mysqli_close($conn);
                
            } catch (Exception $e) {
                $result = ['code' => 1, 'msg' => $e->getMessage()];
            }
            
            echo json_encode($result, JSON_UNESCAPED_UNICODE);
            exit;
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>封闭校区访客管理系统安装</title>
    <link rel="stylesheet" href="inc/css.css?v=<?php echo $version; ?>">
    <script src="inc/js.js?v=<?php echo $version; ?>"></script>
    <style>
        .install-container {
            max-width: 600px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 4px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .install-title {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        .check-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }
        .check-name {
            font-weight: bold;
        }
        .check-value {
            color: #666;
        }
        .check-result {
            font-weight: bold;
        }
        .check-success {
            color: #28a745;
        }
        .check-error {
            color: #dc3545;
        }
        .install-info {
            padding: 15px;
            margin: 15px 0;
            background-color: #f5f5f5;
            border-radius: 4px;
        }
        .install-result {
            padding: 15px;
            margin: 15px 0;
            background-color: #f5f5f5;
            border-radius: 4px;
            display: none;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-title">封闭校区访客管理系统安装</div>
    </div>
    
    <div class="install-container">
        <div class="install-title">系统安装向导</div>
        
        <?php if ($installed): ?>
        <div class="install-info">
            <p>系统已经安装！如需重新安装，请先删除或修改数据库配置。</p>
            <p><a href="index.php" class="btn btn-primary">返回首页</a></p>
        </div>
        <?php //else: ?>
        <div id="check-result"></div>
        
        <div class="install-info">
            <p>请确保以下数据库信息正确：</p>
            <div class="check-item">
                <span class="check-name">数据库主机：</span>
                <span class="check-value"><?php echo $db_host; ?></span>
            </div>
            <div class="check-item">
                <span class="check-name">数据库用户：</span>
                <span class="check-value"><?php echo $db_user; ?></span>
            </div>
            <div class="check-item">
                <span class="check-name">数据库名称：</span>
                <span class="check-value"><?php echo $db_name; ?></span>
            </div>
            <div class="check-item">
                <span class="check-name">数据库端口：</span>
                <span class="check-value"><?php echo $db_port; ?></span>
            </div>
            <p class="mt-10">如需修改，请编辑 inc/conn.php 文件。</p>
        </div>
        
        <div class="form-group">
            <label class="form-checkbox">
                <input type="checkbox" id="demo-data" value="1">
                <span>导入演示数据</span>
            </label>
        </div>
        
        <div class="form-group">
            <button id="install-btn" class="btn btn-primary btn-block">开始安装</button>
        </div>
        
        <div id="install-result" class="install-result"></div>
        <?php endif; ?>
    </div>
    
    <script>
        // 检查环境
        function checkEnvironment() {
            ajaxRequest('install.php?act=check', {}, function(res) {
                if (res.code === 0) {
                    let html = '<div class="install-info">';
                    html += '<div class="check-item"><span class="check-name">PHP版本：</span><span class="check-value">' + res.data.php_version + '</span><span class="check-result ' + (res.data.php_check ? 'check-success' : 'check-error') + '">' + (res.data.php_check ? '通过' : '不支持') + '</span></div>';
                    html += '<div class="check-item"><span class="check-name">MySQL扩展：</span><span class="check-value">' + (res.data.mysqli ? '已安装' : '未安装') + '</span><span class="check-result ' + (res.data.mysqli ? 'check-success' : 'check-error') + '">' + (res.data.mysqli ? '通过' : '不支持') + '</span></div>';
                    html += '<div class="check-item"><span class="check-name">JSON扩展：</span><span class="check-value">' + (res.data.json ? '已安装' : '未安装') + '</span><span class="check-result ' + (res.data.json ? 'check-success' : 'check-error') + '">' + (res.data.json ? '通过' : '不支持') + '</span></div>';
                    html += '<div class="check-item"><span class="check-name">数据库连接：</span><span class="check-value">' + (res.data.db_conn ? '正常' : '失败') + '</span><span class="check-result ' + (res.data.db_conn ? 'check-success' : 'check-error') + '">' + (res.data.db_conn ? '通过' : '不支持') + '</span></div>';
                    html += '</div>';
                    
                    document.getElementById('check-result').innerHTML = html;
                    
                    // 如果所有检查都通过，启用安装按钮，否则禁用
                    const installBtn = document.getElementById('install-btn');
                    if (res.data.php_check && res.data.mysqli && res.data.json && res.data.db_conn) {
                        installBtn.disabled = false;
                    } else {
                        installBtn.disabled = true;
                    }
                }
            });
        }
        
        // 安装系统
        function installSystem() {
            const demoData = document.getElementById('demo-data').checked ? 1 : 0;
            const installBtn = document.getElementById('install-btn');
            const installResult = document.getElementById('install-result');
            
            // 禁用安装按钮并显示加载状态
            installBtn.disabled = true;
            installBtn.innerHTML = '安装中...';
            
            ajaxRequest('install.php?act=install', {demo: demoData}, function(res) {
                // 恢复按钮状态
                installBtn.disabled = false;
                installBtn.innerHTML = '开始安装';
                
                // 显示安装结果
                installResult.style.display = 'block';
                
                if (res.code === 0) {
                    let html = '<div class="check-success" style="font-weight:bold;margin-bottom:10px;">' + res.msg + '</div>';
                    html += '<div class="check-item"><span class="check-name">学生表(stux)：</span><span class="check-result check-success">' + res.data.stux + '</span></div>';
                    html += '<div class="check-item"><span class="check-name">访客表(vist)：</span><span class="check-result check-success">' + res.data.vist + '</span></div>';
                    html += '<div class="check-item"><span class="check-name">设置表(site)：</span><span class="check-result check-success">' + res.data.site + '</span></div>';
                    
                    if (res.data.demo) {
                        html += '<div class="check-item"><span class="check-name">演示数据：</span><span class="check-result check-success">' + res.data.demo + '</span></div>';
                    }
                    
                    html += '<div style="margin-top:15px;"><p>默认管理员账号：admin</p><p>默认管理员密码：123456</p></div>';
                    html += '<div style="margin-top:15px;"><a href="index.php" class="btn btn-primary">进入系统</a></div>';
                    
                    installResult.innerHTML = html;
                } else {
                    installResult.innerHTML = '<div class="check-error">' + res.msg + '</div>';
                }
            });
        }
        
        // 页面加载完成后检查环境
        document.addEventListener('DOMContentLoaded', function() {
            checkEnvironment();
            
            // 绑定安装按钮点击事件
            document.getElementById('install-btn').addEventListener('click', installSystem);
        });
    </script>
</body>
</html>
